/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dieci.database.rawmaterial;

import dieci.database.PersistentObject;
import dieci.database.SessionFactoryUtil;
import dieci.hibernate.HibRawMaterialStock;
import dieci.managers.rawmaterial.RawMaterialManager;
import dieci.system.RawMaterial;
import dieci.system.RawMaterialStock;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Blanco
 */
public class RawMaterialStockHibernateDAO implements RawMaterialStockDAO {
    
    private static Logger logger = Logger.getLogger("RawMaterialStockDAO.log");

    private RawMaterialManager rawMaterialManager = new RawMaterialManager();
    
    @Override
    public List<RawMaterialStock> list()
    {
        List<RawMaterialStock> rawMaterials = new ArrayList<>();

        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
            session.beginTransaction();

            List<HibRawMaterialStock> hibRawMaterialStocks = session.createCriteria(HibRawMaterialStock.class).list();
            for (HibRawMaterialStock dbRawMat : hibRawMaterialStocks) {
                RawMaterial rawMat = findRawMaterialById(dbRawMat.getRawMaterialId());
                RawMaterialStock rawMatStock = new RawMaterialStock(rawMat, dbRawMat.getTotalAmount());
                rawMaterials.add(rawMatStock);
            }

            return rawMaterials;
        }
        catch (Exception e) {

            logger.log(Level.INFO, "Error listando materia prima", e.getMessage());

            throw new IllegalStateException("Error al listar",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }
    }

    @Override
    public void saveOrUpdate(PersistentObject object)
    {
        Session session = null;

        RawMaterialStock rawMat = (RawMaterialStock) object;
        RawMaterialStock found = findByRawMaterialId(rawMat.getRawMaterial().getRawMaterialId());
        try {
            session = SessionFactoryUtil.getInstance().getCurrentSession();
            
            session.beginTransaction();

            HibRawMaterialStock hibRawMaterialStock;
            if (found != null) 
            {
                //UPDATE
                rawMat.getRawMaterial().setRawMaterialId(found.getRawMaterial().getRawMaterialId());
            }
            
            hibRawMaterialStock = new HibRawMaterialStock(rawMat);
            session.saveOrUpdate(hibRawMaterialStock);
            session.getTransaction().commit();

        }
        catch (Exception e) {
            if(session!=null){
                session.getTransaction().rollback();
            }            
            throw new IllegalStateException("Error al guardar o actualizar stock materia prima",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }
    }

    @Override
    public RawMaterialStock findByRawMaterialId(long id)
    {
        RawMaterialStock result = null;
        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
            session.beginTransaction();

            HibRawMaterialStock hibRawMaterialStock = (HibRawMaterialStock) session.createCriteria(HibRawMaterialStock.class).add(Restrictions.eq("rawMaterialId", id)).uniqueResult();
            if (hibRawMaterialStock != null) {
                RawMaterial rawMat = findRawMaterialById(id);
                result = new RawMaterialStock(rawMat, hibRawMaterialStock.getTotalAmount());
            }

        }
        catch (Exception e) {
            throw new IllegalStateException("Error al buscar por id",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }

        return result;
    
    }

    @Override
    public void delete(PersistentObject object)
    {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    private RawMaterial findRawMaterialById(long id){
        return rawMaterialManager.findById((int) id);
    }
    
}
